package com.mf.morefun.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.MoreFunApplication;
import com.mf.morefun.R;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.receiver.NetUtil;
import com.mf.morefun.requestbean.RequestSaveVideoBean;
import com.mf.morefun.util.SendStarOrFlowerNet;
import com.mf.morefun.widget.NetErrorPop;
import com.zhcx.zhcxlibrary.commenplayer.CommenPlayer;
import com.zhcx.zhcxlibrary.commenplayer.listener.IPlayerListener;
import com.zhcx.zhcxlibrary.commenplayer.listener.OnNetListener;
import com.zhcx.zhcxlibrary.commenplayer.ui.ControlLayout;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IMediaPlayer;

public class VideoActivity extends BaseBusActivity {
    @BindView(R.id.player)
    CommenPlayer player;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.ly_content)
    LinearLayout lyContent;
    private String tpBus = "";
    private String tpDetailId = "";
    private String videoUrl = "";
    private SPUtils mSPutil;
    private boolean ignoreNet;
    private SendStarOrFlowerNet mSendStartOrFlowerNet;
    private String userID = "";

    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_videoactivity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSendStartOrFlowerNet = new SendStarOrFlowerNet(VideoActivity.this, lyContent);
        mSPutil = new SPUtils(getApplicationContext());
        tpBus = getIntent().getStringExtra("TPBUS");
        tpDetailId = getIntent().getStringExtra("TPDETAILID");
        videoUrl = getIntent().getStringExtra("VIDEO");
        userID = getIntent().getStringExtra(Configuration.USERID);
        if (!StringUtils.isEmpty(videoUrl)) {
            initPlayer();
            player.play(videoUrl);
        }
    }

    private void initPlayer() {
        player.setLive(false);
        player.setOnNetListener(new OnNetListener() {
            @Override
            public void onIgnoreMobileNet() {
                ignoreNet = true;
            }
        }).setOnPlayerListener(new IPlayerListener() {
            @Override
            public void onLoading() {
                player.getControl().setState(ControlLayout.STATE_LOADING);
            }

            @Override
            public void onCompletion(IMediaPlayer mp) {
                player.getControl().setState(ControlLayout.STATE_COMPLETION);
                //播放完了
                if (!StringUtils.isEmpty(tpBus) || !StringUtils.isEmpty(tpDetailId)) {
                    initSaveVideo(videoUrl);
                }else {
                    if (!StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))){
                        mSendStartOrFlowerNet.initGetFlower(20
                                , mSPutil.getString(Configuration.USERID),
                                getIntent().getStringExtra("BOOKID"),
                                "1", "5");
                    }
                }
            }

            @Override
            public void onPrepared(IMediaPlayer mp) {
                //代表移动网
                if (!ignoreNet && NetUtil.getNetWorkState(VideoActivity.this) == 0) {
                    player.pause();
                    player.getControl().setState(ControlLayout.STATE_MOBILE_NET);
                } else {
                    player.getControl().setState(ControlLayout.STATE_PREPARED);
                }
            }

            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                player.getControl().setState(ControlLayout.STATE_ERROR);
                return false;
            }

            @Override
            public boolean onInfo(IMediaPlayer mp, int what, int extra) {
                return false;
            }

            @Override
            public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sarNum, int sarDen) {

            }
        });

    }

    private void initSaveVideo(String videoPath) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.SAVEVIDEO);
        RequestSaveVideoBean requestSaveVideoBean = new RequestSaveVideoBean();
        requestSaveVideoBean.setAudio(videoPath);
        if (StringUtils.isEmpty(getIntent().getStringExtra("type"))) {
            requestSaveVideoBean.setType("4");
        } else {
            requestSaveVideoBean.setType(getIntent().getStringExtra("type"));
        }
        requestSaveVideoBean.setTpBus(tpBus);
        RequestSaveVideoBean.TpDetailBean tpDetailBean = new RequestSaveVideoBean.TpDetailBean();
        tpDetailBean.setId(tpDetailId);
        requestSaveVideoBean.setTpDetail(tpDetailBean);
        RequestSaveVideoBean.UserBean userBean = new RequestSaveVideoBean.UserBean();
        userBean.setId(userID);
        requestSaveVideoBean.setUser(userBean);
        RequestSaveVideoBean.ClassBelongBean classBelongBean = new RequestSaveVideoBean.ClassBelongBean();
        classBelongBean.setId(getIntent().getStringExtra("CLASSID"));
        requestSaveVideoBean.setClassBelong(classBelongBean);
        RequestSaveVideoBean.TpBean tpBean = new RequestSaveVideoBean.TpBean();
        tpBean.setId(getIntent().getStringExtra("TP"));
        requestSaveVideoBean.setTp(tpBean);
        params.setBodyContent(JSON.toJSONString(requestSaveVideoBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(getIntent().getStringExtra("BOOKID"))){
                            mSendStartOrFlowerNet.initGetFlower(20
                                    , userID,
                                    getIntent().getStringExtra("BOOKID"),
                                    "1", "5");
                        }
                    } else {
                        ToastUtils.show(getApplicationContext(), resultBean.getMessage(), 100);
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(VideoActivity.this);
                    errorPop.showPop("");
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }

    @OnClick(R.id.iv_back)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
        }
    }

    @Override
    protected void onPause() {
        if (player != null) {
            player.onPause();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void finish() {
        if (player != null) {
            player.onDestroy();
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (null != mSendStartOrFlowerNet){
            mSendStartOrFlowerNet.stopAnim();
        }
    }
}
